<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <!-- 手机号和验证码输入框 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="info.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="info.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          :loading="loading"
          type="info"
          loading-text="加载中..."
          round
          block
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入接口
import { loginAPI } from "@/api";

export default {
  data() {
    return {
      loading: false,
      info: {
        mobile: "13911111111",
        code: "246810",
      },

      rules: {
        mobile: [
          //   required代表必填,
          { required: true, message: "请输入手机号" },
          { pattern: /^1[2-9]\d{9}$/, message: "请输入正确的手机号" },
        ],

        code: [
          { required: true, message: "请输入验证码" },
          { pattern: /^\d{6}$/, message: "请输入6位数的验证码" },
        ],
      },
    };
  },

  methods: {
    async onSubmit() {
      this.loading = true;
      try {
        let res = await loginAPI(this.info);
        //   console.log(res);
        this.$store.commit("changeToken", res.data.data);
        this.$toast.success("登录成功!");
        // 因为不管你是怎样来的重新登录肯定都需要加载最新的登录账号信息
        this.$store.commit("changeUserInfo", {});
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back);
        } else {
          this.$router.push("/layout/home");
        }
      } catch {
        this.$toast.fail("账号或密码错误");
      }
      this.loading = false;
    },
  },
};
</script>

<style>
</style>